<template>
  <div>
    <div class="title">
      {{ this.$route.query.activityId ? "编辑" : "新增" }}活动
    </div>
    <el-form
      :model="ruleForm"
      :rules="rules"
      ref="fromRef"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="活动名称" prop="name">
        <el-input
          v-model="ruleForm.name"
          maxlength="5"
          show-word-limit
          style="width: 320px"
        ></el-input>
        <span class="remark">(活动名称不超过5个字)</span>
      </el-form-item>
      <el-form-item
        label="有效时间"
        prop="useDateValue"
        style="margin-top: 30px"
      >
        <el-date-picker
          v-model="ruleForm.useDateValue.startTime"
          type="datetime"
          placeholder="开始日期"
          style="width: 220px"
          :disabled="isChecked"
          :picker-options="pickerOptions"
        ></el-date-picker>
        <span style="margin-left: 10px; color: #ccc">至</span>
        <el-date-picker
          v-model="ruleForm.useDateValue.endTime"
          type="datetime"
          placeholder="结束日期"
          style="width: 220px; margin-left: 10px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="预热时间" prop="preTime" style="margin-top: 30px">
        <el-input-number
          :min="0"
          step-strictly
          :step="1"
          :controls="false"
          v-model="ruleForm.preTime"
          style="width: 180px"
          @input="shippingKeydown"
        >
          <span slot="append">小时</span>
        </el-input-number>
        <span class="remark"
          >输入值大于0时该活动在商详页展示活动信息，0为不预热，预热时间最多24小时</span
        >
      </el-form-item>
      <el-form-item label="商品选择" prop="actRules" style="margin-top: 30px">
        <ApointGoods
          ref="apointComp"
          :content="activityContent"
          :actType="actType"
        />
      </el-form-item>
      <el-form-item label="封面海报" prop="img" style="margin-top: 30px">
        <div class="product" style="display: flex">
          <el-upload
            class="productImg__uploader product__productImg"
            :auto-upload="false"
            :on-change="addUploadBigProductImg"
            action=""
            :show-file-list="false"
            style="width: 250px; height: 120px"
          >
            <img
              v-if="ruleForm.img"
              :src="ruleForm.img"
              class="product__productImg"
              style="width: 250px; height: 120px"
            />
            <i
              class="el-icon-plus product__productImg--uploader--icon"
              v-if="!ruleForm.img"
              style="width: 250px; line-height: 100px"
            ></i>
            <div
              class="product__productImg--uploader--add"
              v-if="!ruleForm.img"
              style="top: 70px; left: 100px"
            >
              添加图片
            </div>
          </el-upload>
          <div
            class="text-info fs-12"
            style="
              color: rgba(69, 64, 60, 0.6);
              display: flex;
              align-items: flex-end;
              margin-left: 20px;
            "
          >
            (尺寸建议750x375（长方形模式）像素以上，大小1M以下,图片格式支持
            png,jpg,jpeg,gif)
          </div>
        </div>
      </el-form-item>
      <el-form-item label="活动描述" prop="desc" style="margin-top: 30px">
        <el-input
          v-model="ruleForm.desc"
          maxlength="15"
          show-word-limit
          style="width: 320px"
        ></el-input>
        <span class="remark">(活动描述最多15个字)</span>
      </el-form-item>
    </el-form>
    <div class="pageButtom">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Ref } from "vue-property-decorator";
import DateUtil from "@/store/modules/date";
import { readFile, advanceGetImage } from "@/store/modules/voidImg";
import { upLoad } from "@/api/index";
import ApointGoods from "../common/ApointGoods.vue";
import {
  addActivity,
  getActivityById,
  editActivityById,
} from "@/api/chainActivity/chainActivity";
Component.registerHooks(["beforeRouteLeave"]);

@Component({
  components: {
    ApointGoods,
  },
})
export default class AddChainActivity extends Vue {
  @Ref()
  readonly fromRef: HTMLFormElement;

  @Ref()
  readonly apointComp: HTMLFormElement;

  actType = "AddChainActivity";

  ruleForm = {
    name: "",
    useDateValue: {
      startTime: "" as any,
      endTime: "" as any,
    },
    preTime: 0 as any,
    img: "",
    desc: "",
    status: 0,
    id: "",
  };

  /** 编辑室获取到接龙详情 */
  activityContent = {};

  /** 开始时间是否可选 */
  isChecked = false;

  /** 是否有退出提示 */
  saveFlag = false;

  rules = {
    name: [{ required: true, message: "请输入活动名称", trigger: "blur" }],
    useDateValue: [
      {
        validator: this.validatePass,
        required: true,
        trigger: "blur",
      },
    ],
    preTime: [{ required: true, message: "请输入预热时间", trigger: "blur" }],

    actRules: [
      { validator: this.rulevalidate, required: true, trigger: "blur" },
    ],
    img: [{ required: true, message: "请上传封面海报", trigger: "blur" }],
    desc: [{ required: true, message: "活动描述不能为空", trigger: "blur" }],
  };

  validatePass(rule, value, callback) {
    const start = new Date(value.startTime).getTime();
    const now = new Date(new DateUtil("").getYMD(new Date())).getTime();
    if (!value.endTime || !value.startTime) {
      callback(new Error("请输入活动时间"));
    } else {
      if (value.startTime.getTime() > value.endTime.getTime()) {
        callback(new Error("结束时间不能小于开始时间"));
      }
      if (start < now) {
        if (!this.$route.query.activityId) {
          callback(new Error("开始时间不能小于当前时间"));
        }
      }
    }
  }

  rulevalidate() {
    console.log("test");
  }

  pickerOptions = {
    disabledDate(time) {
      const now = new Date(new Date().toLocaleDateString()).getTime();
      return time.getTime() < now;
    },
  };

  mounted() {
    if (this.$route.query.activityId) {
      this.getDeatil(this.$route.query.activityId);
    }
  }

  /**
   * 编辑时获取数据
   */
  getDeatil(id) {
    getActivityById(id, {})
      .then((res) => {
        this.ruleForm.name = res.data.solitaireActivityVo.name;
        this.ruleForm.preTime = res.data.solitaireActivityVo.preheatHour;
        this.ruleForm.img = res.data.solitaireActivityVo.coverPoster;
        this.ruleForm.desc = res.data.solitaireActivityVo.content;
        this.ruleForm.status = res.data.solitaireActivityVo.status;
        this.isChecked =
          res.data.solitaireActivityVo.status === 1 ? true : false;
        this.ruleForm.id = res.data.solitaireActivityVo.id;
        this.ruleForm.useDateValue.startTime = new Date(
          res.data.solitaireActivityVo.startTime,
        );
        this.ruleForm.useDateValue.endTime = new Date(
          res.data.solitaireActivityVo.endTime,
        );
        this.activityContent = res.data;
      })
      .catch((err) => {
        this.$message.error(err || "网络错误");
      });
  }

  /**
   * 上传海报
   */
  async addUploadBigProductImg(file) {
    const whiteList = ["image/jpeg", "image/jpg", "image/png", "image/gif"];

    const isLt1M = file.size < 1 * 1024 * 1024;
    if (!whiteList.includes(file.raw.type)) {
      this.$message.error("上传文件只能是 JPG或PNG 格式!");
      return;
    }
    if (!isLt1M) {
      this.$message.error("上传文件大小不能超过 1MB!");
      return;
    }

    const imgFile = await readFile(file.raw);
    const newImg = await advanceGetImage(imgFile);

    if (newImg.image.width !== 750 || newImg.image.height !== 375) {
      this.$message.error("海报图片长宽应为750 * 375");
      return;
    }

    const res = await upLoad({
      file: file.raw,
    });
    this.ruleForm.img = res.data;
  }

  async save() {
    this.formValid();

    const check = this.checkSecond();
    if (!check) {
      return;
    }

    let list = [];
    if (this.apointComp.goodRadio === 1) {
      list = this.apointComp.joinList;
    } else if (this.apointComp.goodRadio === 2) {
      list = this.apointComp.unJoinList;
    }

    if (list) {
      list.forEach((item) => {
        item.productId = item.id;
      });
    }

    if (this.apointComp.goodRadio === 1 || this.apointComp.goodRadio === 2) {
      if (list.length === 0) {
        this.$message.error("请选择商品");
        return;
      }
    }

    const param = {
      content: this.ruleForm.desc,
      coverPoster: this.ruleForm.img,
      name: this.ruleForm.name,
      preheatHour: this.ruleForm.preTime,
      productType: this.apointComp.goodRadio,
      id: this.ruleForm.id,
      activityProducts: list,
      startTime: new DateUtil("").getYMDHMSs(
        this.ruleForm.useDateValue.startTime,
      ),
      endTime: new DateUtil("").getYMDHMSs(this.ruleForm.useDateValue.endTime),
      status: this.ruleForm.status,
    };
    if (this.$route.query.activityId && param.status !== 2) {
      this.editActivity(param);
      return;
    }

    if (param.status === 2) {
      delete param.id;
    }
    await addActivity(param)
      .then(() => {
        this.$message.success("发布成功");
        this.saveFlag = true;
        this.$router.push({ name: "ChainIndex" });
      })
      .catch((err) => {
        this.$message.error(err || "网络错误");
      });
  }

  formValid() {
    return this.fromRef.validate();
  }

  checkSecond() {
    const start = this.ruleForm.useDateValue.startTime.getTime();
    const end = this.ruleForm.useDateValue.endTime.getTime();
    new Date(new DateUtil("").getYMD(new Date())).getTime();

    const lastDay = (end - start) / 1000 / 60 / 60 / 24;
    if (lastDay > 31) {
      this.$message.error("活动时间最多持续一个月");
      return false;
    }
    if (start > end) {
      return false;
    }
    if (!this.ruleForm.name) {
      return false;
    }
    const preTimeReg = /^[+]{0,1}(\d+)$/;
    if (
      !preTimeReg.test(this.ruleForm.preTime) ||
      Number(this.ruleForm.preTime) < 0 ||
      Number(this.ruleForm.preTime) > 24
    ) {
      this.$message.error("预热时间需为0-24的整数");
      return false;
    }
    if (!this.ruleForm.img) {
      return false;
    }
    if (!this.ruleForm.desc) {
      return false;
    }
    return true;
  }

  editActivity(param) {
    editActivityById(param)
      .then(() => {
        this.$message.success("编辑成功");
        this.saveFlag = true;
        this.$router.push({ name: "ChainIndex" });
      })
      .catch((err) => {
        this.$message.error(err || "网络错误");
      });
  }

  /**
   * 设置 预热时间
   */
  shippingKeydown(e) {
    if (+e < 0) {
      this.ruleForm.preTime = 0;
    } else {
      this.ruleForm.preTime = +e;
    }
  }

  /**
   * 取消操作
   */
  cancel() {
    this.saveFlag = false;
    this.$router.push({ name: "ChainIndex" });
  }

  beforeRouteLeave(to, from, next) {
    if (this.saveFlag) {
      next();
      return;
    }
    this.$confirm(
      `确定要退出${
        this.$route.query.activityId ? "编辑" : "发布"
      }接龙活动?退出后，未保存的信息将不会保留!`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    ).then(() => {
      next();
    });
  }
}
</script>

<style lang="scss" scoped>
.title {
  margin: 10px 0px;
  font-weight: bold;
  font-size: 14px;
  margin-bottom: 20px;
  margin-left: 10px;
}

.remark {
  margin-left: 20px;
  color: #9b9b9b;
}

.productImg__uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.productImg__uploader:hover {
  border-color: #409eff;
}

.product__productImg {
  width: 100px;
  height: 100px;
  display: inline-block;
}

.product__productImg--uploader--icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 80px;
  text-align: center;
}

.product__productImg--uploader--add {
  position: absolute;
  top: 55px;
  left: 20px;
  color: #7f7f7f;
}

.pageButtom {
  margin-top: 80px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
